package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func buildByArr(nums []int) *ListNode {
	if len(nums) == 0 {
		return nil
	}

	root := &ListNode{Val: nums[0]}
	cur := root
	for i := 1; i < len(nums); i++ {
		cur.Next = &ListNode{Val: nums[i]}
		cur = cur.Next
	}

	return root

}

func main() {
	node := buildByArr([]int{1, 2, 3, 3, 4, 4, 5})

	printListNode(node)
	fmt.Println("\n------")
	node2 := deleteDuplicates(node)
	printListNode(node2)
}

func printListNode(node *ListNode) {
	for node != nil {
		fmt.Printf("%d->", node.Val)
		node = node.Next
	}
	fmt.Print("nil")
}

// 		  pre                       cur
// 1  ---- 2  ------2 ----- 2 -------3
func deleteDuplicates(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}

	dummyHead := &ListNode{0, head}
	pre, cur := dummyHead, head

	for cur != nil && cur.Next != nil {
		if pre.Next.Val == cur.Next.Val {
			for cur != nil && cur.Next != nil && pre.Next.Val == cur.Next.Val {
				cur = cur.Next
			}

			pre.Next = cur.Next
			cur = cur.Next
		} else {
			pre = pre.Next
			cur = cur.Next
		}

	}

	return dummyHead.Next
}
